'use strict';

const Controller = require('egg').Controller;
const fs = require('fs');
const path = require('path');
class HomeController extends Controller {
  async updateuser() { // 通过verifyToken校验才能执行该函数
    // 获取用户信息
    const { id, phone, email, password, type, faceimage } = this.ctx.userInfo;
    // console.log(this.ctx.userInfo, this.ctx.request.body);
    const res = await this.app.mysql.update('user', {
      id,
      phone,
      email,
      password,
      type,
      faceimage,
      ...this.ctx.request.body,
    });
    if (res.changedRows) {
      this.ctx.body = {
        code: 'SUCCESS',
        status: 200,
        msg: '更新成功',
      };
    }
  }
  async uploadimage() {
    const file = this.ctx.request.files[0];
    const data = fs.readFileSync(file.filepath);
    const filename = `file_${Date.now()}_${file.filename.match(/\.\w+$/)[0]}`;
    const targetPath = path.join(__dirname, '../public/images', filename);
    fs.writeFileSync(targetPath, data);
    this.ctx.body = {
      code: 'SUCCESS',
      status: 200,
      msg: '头像上传成功',
      data: {
        url: '/public/images/' + filename,
      },
    };
  }
  async index() { // 通过verifyToken校验才能执行该函数
    this.ctx.body = {
      code: 'SUCCESS',
      status: 200,
      msg: '获取用户信息成功',
      data: this.ctx.userInfo,
    };
  }
  async login() {
    const { body } = this.ctx.request;
    const { service } = this.ctx;
    const errors = this.app.validator.validate({ password: 'password', phone: 'phone' }, body);
    if (errors) {
      this.ctx.status = 417;
      this.ctx.body = {
        code: 'FAIL',
        status: 417,
        msg: '校验未通过',
        data: errors,
      };
      return;
    }
    // 查数据库
    const res = await service.user.login(body);
    if (res) {
      // 登录成功
      const { sign } = this.ctx.helper.token;
      this.ctx.status = 200;
      this.ctx.body = {
        code: 'SUCCESS',
        msg: '登录成功',
        status: 200,
        data: {
          token: sign({ ...res }),
        },
      };
      return;
    }
    this.ctx.status = 200;
    this.ctx.body = {
      code: 'FAIL',
      status: 200,
      msg: '邮箱或手机号或密码输入有误！',
    };
    return;

  }
}

module.exports = HomeController;
